'''
Created on Jul 6, 2010

@author: oabalbin
'''

import sys
import numpy as np
from optparse import OptionParser
from collections import deque, defaultdict

def read_nodes_dict(inputfile,logval=False):
    """
    """
    all_prot_nodes, all_nodes=defaultdict(),defaultdict()
    header = inputfile.next()
    node_scale=1 #1000
    
    for line in inputfile:
        line = line.strip('\n')
        fields = line.split('\t')
        weight =float(fields[1])
        
        if weight==0.0:
            all_prot_nodes[fields[0]] = weight
        else:
            if not logval:
                all_prot_nodes[fields[0]] = np.abs(np.log(weight))
            else:
                all_prot_nodes[fields[0]] = np.abs(weight)
        
    prot_node_weight_denominator = np.sum(np.array(all_prot_nodes.values()))

    for node, weight in all_prot_nodes.iteritems():
        all_nodes[node] = (weight/prot_node_weight_denominator)*node_scale
        
    return all_nodes

def write_normalized_weight_nodes(node_dict, outputfile):
    
    for node,weight in node_dict.iteritems():
        line = [node,weight]
        outputfile.write(",".join(map(str,line)).replace(',','\t')+'\n')
        
if __name__ == '__main__':
    '''
    It generates a normalized nodes file= node_weight/sum(all_nodes_weight)*scale_factor
    
    '''
    optionparser = OptionParser("usage: %prog [options] ")
    optionparser.add_option("-n", "--nodesFile", dest="nodesFile",
                            help="nodesFile file for all files to use")
    optionparser.add_option("-l", "--logval", dest="logval",
                            help="annotation file for all files to use")
    
    (options, args) = optionparser.parse_args()
    
    inputfile1 = options.nodesFile
    outputfile1 = options.nodesFile+'_node_norm'
    
    logval=True
    nodedictionary = read_nodes_dict(open(inputfile1),logval)
    write_normalized_weight_nodes(nodedictionary,open(outputfile1,'w'))
    